package com.chinaway.mobile.authcode;

import java.awt.image.BufferedImage;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

import com.chinaway.mobile.authcode.util.Filter;
import com.chinaway.mobile.authcode.util.Tools;

public class AuthCodeDiscernZjimpl implements AuthCodeDiscern{
	
	private  String zjDownImagePath ="E:\\Decheckimg\\zj\\checkImg\\" ; 
	@Override
	public String discern(BufferedImage image, boolean print) {
		String name  = "" ;
		if (print) {
			name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
			Tools.writeImageToFile(zjDownImagePath + name + ".jpg", image);
			Filter.blackAndWhiteZjFilter(image);
//			Tools.writeImageToFile(zjDownImagePath + name + "-a.bmp", image);
		}
		Filter.blackAndWhiteZjFilter(image);
		BufferedImage[] arrayImg =  Tools.getZjCheckCodes(image);
		Map<BufferedImage, String> map = null;
		String result = "";
		try {
			map = Tools.loadTrainData("zj");
			int i = 0 ;
			for (BufferedImage bi : arrayImg) {
				if(print){
//					Tools.writeImageToFile(zjDownImagePath + name + i + "-b.bmp", bi);
				}
				i++ ;
				result += Tools.getZjSingleCharOcr(bi, map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		String randCode =  filterString(result) ;
	    return randCode;
	}
	public  String filterString(String str){
		str = StringUtils.trimToNull(str);
		if(StringUtils.isBlank(str))return "" ;
		StringBuffer sb = new StringBuffer();
		String regEx = "[0-9A-Z]";
		Pattern p = Pattern.compile(regEx);
		String[] array_s = str.split("");
		for (String s : array_s) {
			Matcher m = p.matcher(s);
			if (m.find()) {
				sb.append(s);
			}
		}
        String s = sb.toString() ;
        s = StringUtils.trimToNull(s);
        if(StringUtils.isNotBlank(s)){
        	if(s.length()!= 5){
        		 s= "" ;
        	}
        }
        return s ;
	}
	public void setZjDownImagePath(String zjDownImagePath) {
		this.zjDownImagePath = zjDownImagePath;
	}
 
}
